package org.rbac.content;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.rbac.content.ApplicationContent.CONTENT;
import org.rbac.content.define.ContentDefine;
import org.rbac.content.define.RbacKeyDefine;
import org.rbac.content.define.RbacKeyDefine.keys;
import org.rbac.serv.CommonServices;
import org.rbac.serv.LogServices;
import org.rbac.vo.Action;
import org.rbac.vo.User;
import org.springframework.stereotype.Component;
/**
 * 
*  <pre>    
* 类名称：RbacApplicationContent 
* 类描述：   
* 创建人：陈国祥   (kingschan)
* 创建时间：2015-3-31 上午11:24:21   
* 修改人：Administrator   
* 修改时间：2015-3-31 上午11:24:21   
* 修改备注：   
* @version V1.0
* </pre>
 */
@SuppressWarnings("unchecked")
@Component("RbacApplicationContent")
public class RbacApplicationContent implements ContentDefine{
  private  Logger log = Logger.getLogger(RbacApplicationContent.class);
    

    
    @Resource(name="LogServices")
    private LogServices logserv;
    @Resource(name="CommonServices")
    private CommonServices commonserv;

    /*
     * (non-Javadoc)
     * @see org.rbac.content.define.ContentDefine#getApplicationMapping(javax.servlet.http.HttpServletRequest)
     */
    @Override
    public Map<String, Action> getApplicationMapping() throws Exception {
        Map<String, Action> map=(Map<String, Action>) CacheContent.getInstance().get(RbacKeyDefine.getKey(keys.APPLICATION_URL_MAPPING),CONTENT.APPLICATION);
        if (null==map) {
            setApplicationMapping();
            map=(Map<String, Action>) CacheContent.getInstance().get(RbacKeyDefine.getKey(keys.APPLICATION_URL_MAPPING),CONTENT.APPLICATION);
        }
        return map;
    }
    /*
     * (non-Javadoc)
     * @see org.rbac.content.define.ContentDefine#getActionByUrl(javax.servlet.http.HttpServletRequest, java.lang.String)
     */
    @Override
    public Action getActionByUrl(String name) throws Exception {
        return getApplicationMapping().get(name);
    }
    /*
     * (non-Javadoc)
     * @see org.rbac.content.define.ContentDefine#getUserAccessBtns(javax.servlet.http.HttpServletRequest, java.lang.String)
     */
    
    @Override
    public Map<String, List<Object>> getUserAccessBtns(HttpServletRequest req)
            throws Exception {
        return (Map<String, List<Object>>) req.getSession().getAttribute(RbacKeyDefine.getKey(keys.USER_BTN_AUTHORITY_KEY));
    }
    /*
     * (non-Javadoc)
     * @see org.rbac.content.define.ContentDefine#getCurrentPageBtns(javax.servlet.http.HttpServletRequest, java.lang.String)
     */
    @Override
    public List<Object> getCurrentPageBtns(HttpServletRequest req, String actionName)
            throws Exception {
        return getUserAccessBtns(req).get(actionName);
    }
    /*
     * (non-Javadoc)
     * @see org.rbac.content.define.ContentDefine#getUserAccessAction(javax.servlet.http.HttpServletRequest)
     */
    @Override
    public Map<String, Object> getUserAccessAction(HttpServletRequest req) throws Exception {
        return (Map<String, Object>) req.getSession().getAttribute(RbacKeyDefine.getKey(keys.USER_URL_AUTHORITY_KEY));
    }
    /*
     * (non-Javadoc)
     * @see org.rbac.content.define.ContentDefine#loadApplicationMappingData(javax.servlet.ServletContext)
     */
    @Override
    public Map<String, Action> loadApplicationMappingData()throws Exception {
      return commonserv.loadApplicationMappingData();
    }
    /*
     * (non-Javadoc)
     * @see org.rbac.content.define.ContentDefine#setApplicationMapping(javax.servlet.ServletContext, java.util.Map)
     */
    @Override
    public void setApplicationMapping() throws Exception {        
        CacheContent.getInstance().put(RbacKeyDefine.getKey(keys.APPLICATION_URL_MAPPING), loadApplicationMappingData(),CONTENT.APPLICATION);
    }
    /*
     * (non-Javadoc)
     * @see org.rbac.content.define.ContentDefine#log(javax.servlet.http.HttpServletRequest)
     */
    @Override
    public Boolean log(String ip,String method,String uri,Integer uid,String data,String remark,boolean pass,long seconds,String referer) {
       return logserv.log(ip, method, uri, uid, data, remark, pass, seconds,referer);
    }
   
   

    /**
     * 得到客户端IP
     * 
     * @param request
     * @return
     */
    @Override
    public String getClientIP(HttpServletRequest request) {
        String ipAddress = null;
        ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1")) {
                // 根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }

        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }
    /**
     * 得到当前登录的用户
     * @param req
     * @return
     */
    public static User getCurrentUser(HttpServletRequest req){
        return (User) req.getSession().getAttribute(RbacKeyDefine.getKey(keys.CURRENT_USER));
    }
    @Override
    public void loadDictionary(ServletContext content) throws Exception {
        List<Map<String, Object>> lis =commonserv.loadDictionary();
        if (null!=lis) {
            for (Map<String, Object> map : lis) {
                content.setAttribute(map.get("key").toString(), map.get("value").toString());
                log.info(String.format("加载数据字典:【%s】值【%s】", map.get("key").toString(), map.get("value").toString()));
            }
        }
        
    }
}
